<template>
  <div>
    <a-card>
      <h2>邀请码</h2>
      <a-divider />
      <a-button @click="addCode" type="primary">添加一条</a-button>
      <div class="mt-10">
        <a-table
          :dataSource="list"
          :columns="columns"
          :pagination="false"
          bordered
        >
          <template #operation="{record}">
            <a-button
              v-if="record.isUsed"
              @click="deleteCode(record._id)"
              type="danger"
              >删除</a-button
            >
          </template>
          <template #isUsed="{record}">
            {{ record.user ? '已使用' : '未使用' }}
          </template>
        </a-table>
      </div>
      <div class="mt-10">
        <a-pagination
          v-model:current="curPage"
          :page-size="pageSize"
          :total="total"
          @change="setPage"
        />
      </div>
    </a-card>
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import { defineComponent, onMounted, ref } from 'vue'
import { handleResult } from '../helpers/utils'
import { inviteCodeService } from '../services'
export default defineComponent({
  setup () {
    const curPage = ref(1)
    const total = ref(0)
    const pageSize = ref(5)
    const list = ref([])
    const columns = [
      {
        title: '邀请码',
        dataIndex: 'code'
      },
      {
        title: '是否使用',
        slots: {
          customRender: 'isUsed'
        }
      },
      {
        title: '操作',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    const setPage = page => {
      curPage.value = page
      getlist()
    }

    const getlist = async () => {
      const res = await inviteCodeService.getList(curPage.value, pageSize.value)
      handleResult(res).success(({ data: { list: l, total: t } }) => {
        l.forEach(item => {
          item.key = item._id
          item.isUsed = item.user === ''
        })
        list.value = l
        total.value = t
      })
    }

    onMounted(() => {
      getlist()
    })

    const addCode = async () => {
      const res = await inviteCodeService.addOneInviteCode()
      handleResult(res).success(({ msg }) => {
        message.success(msg)
        getlist()
      })
    }

    const deleteCode = async id => {
      const res = await inviteCodeService.deleteById(id)
      handleResult(res).success(({ msg }) => {
        message.success(msg)
        getlist()
      })
    }

    return {
      curPage,
      total,
      pageSize,
      list,
      columns,
      setPage,
      deleteCode,
      addCode
    }
  }
})
</script>

<style lang="scss" scoped></style>
